package com.xiaonei;

import java.io.IOException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.w3c.dom.Document;

import com.xiaonei.api.ProfileField;
import com.xiaonei.api.XiaoneiException;
import com.xiaonei.api.XiaoneiRestClient;
import com.xiaonei.api.schema.Friend;
import com.xiaonei.api.schema.FriendsGetFriendsResponse;
import com.xiaonei.api.schema.RequestsSendRequestResponse;
import com.xiaonei.api.schema.UsersGetInfoResponse;

import edu.maplef.bookwild.utils.StrCharUtil;

public class ClientTest extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public static String PARAM_XN_SIG_IN_IFRAME = "xn_sig_in_iframe";

	public static String PARAM_XN_SIG_TIME = "xn_sig_time";

	public static String PARAM_XN_SIG_ADDED = "xn_sig_added";

	public static String PARAM_XN_SIG_USER = "xn_sig_user";

	public static String PARAM_XN_SIG_SESSION_KEY = "xn_sig_session_key";

	public static String PARAM_XN_SIG_API_KEY = "xn_sig_api_key";

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ClientTest() {
		super();
		// TODO Auto-generated constructor stub
	}

	private List<Friend> getFriend(XiaoneiRestClient client) throws Exception {
		client.friends_getFriends();
		FriendsGetFriendsResponse resp = (FriendsGetFriendsResponse) client
				.getResponsePOJO();
		List<Friend> friends = resp.getFriend();
		return friends;
		//		    for (Friend friend : friends) {
		//		        System.out.println("friends|getFriends|Id|"+friend.getId());
		//		        System.out.println("friends|getFriends|Name|"+friend.getName());
		//		        System.out.println("friends|getFriends|Headurl|"+friend.getHeadurl());
		//		    }    	
	}

	private String buildUserInfo(int id) {
		StringBuffer sb = new StringBuffer();
		sb.append("<div align=\"center\">\n");
		sb.append("图片：<xn:profile-pic uid=\"");
		sb.append(id);
		sb.append("\" linked=\"true\" size=\"tiny\"/><br>\n");
		sb.append("姓名：<xn:name uid=\"" + id
				+ "\" linked=\"true\" shownetwork=\"true\" />\n");
		sb.append("</div>\n");
		return sb.toString();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		response.setHeader("Charset", "utf-8");
		response.setHeader("Cache-Control", "no-cache");
		request.setCharacterEncoding("UTF-8");

		JSONObject json = new JSONObject();

		String cmd = StrCharUtil.formatNullStr(request.getParameter("cmd"));
		String callback = StrCharUtil.formatNullStr(request
				.getParameter("callback"));

		String sessionKey = request.getParameter(PARAM_XN_SIG_SESSION_KEY);

		XiaoneiRestClient client = new XiaoneiRestClient(
				"90222bf15c3a4d2bb362c572461c98be",
				"918f9b63862b4f808640ebf89cf4104f", sessionKey);
		//client.setDebug(true);

		try {
			if ("getfriends".equals(cmd)) {
				JSONArray jj = JSONArray.fromObject(getFriend(client));
				json.put("res", jj.toString());
			} else if ("myinfor".equals(cmd)) {
				int loggedInUserId = 0;
				try {
					loggedInUserId = client.users_getLoggedInUser();
					EnumSet<ProfileField> enumFields = EnumSet.of(
							ProfileField.NAME, ProfileField.HOMETOWN_LOCATION,
							ProfileField.BIRTHDAY, ProfileField.HEADURL,
							ProfileField.MAINURL, ProfileField.SEX,
							ProfileField.STAR, ProfileField.TINYURL,
							ProfileField.ZIDOU,
							ProfileField.UNIVERSITY_HISTORY,
							ProfileField.WORK_HISTORY);

					Document doc = client.users_getInfo(loggedInUserId,
							enumFields);
					json.put("xml", doc.toString());
					UsersGetInfoResponse loggedUserGetInfoRes = (UsersGetInfoResponse) client
							.getResponsePOJO();
					json.put("res", JSONArray.fromObject(loggedUserGetInfoRes
							.getUser()));
				} catch (XiaoneiException e) {
					e.printStackTrace();
				}
			} else if ("invite".equals(cmd)) {
				List<Integer> userIds = new ArrayList();
				List<Friend> friends = getFriend(client);

				for (Friend f : friends) {
					userIds.add(f.getId());
				}

				client.requests_sendRequest(userIds);
				request.setAttribute("uids", client.getRawResponse());
				//进一步看看都成功邀请了哪些朋友
				RequestsSendRequestResponse resp = (RequestsSendRequestResponse) client
						.getResponsePOJO();

				List<Integer> uids = resp.getUid();

				json.put("res", JSONArray.fromObject(uids));
			}
			if (json != null) {
				if (callback.equals("")) { //没有回调函数
					response.getWriter().println(json.toString());
				} else {
					response.setContentType("text/javascript;charset=utf-8");
					response.getWriter().println(
							callback + "(" + json.toString() + ")");
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doGet(request, response);
	}

}
